package com.laogao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laogao.entity.SelectOptions;
import com.laogao.mapper.OptionMapper;
import com.laogao.service.OptionService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

@Service
public class OptionServiceImpl extends ServiceImpl<OptionMapper, SelectOptions> implements OptionService {

    private static final int BATCH_SIZE = 2000;

    @Override
    @Async("taskExecutor")
    // 强制新事务
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public CompletableFuture<Void> saveBatchAsync(List<SelectOptions> questionList) {
        try {
            // 调用父类的saveBatch方法执行批量插入
            saveBatch(questionList, BATCH_SIZE);
        } catch (Exception e) {
            log.error("批量保存题目失败，原因：", e);
            // 包装为 CompletionException，便于上层捕获
            throw new CompletionException(e);
        }
        return CompletableFuture.completedFuture(null);
    }
}